package Java.BlackHorse.a04FileTest;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Test5 {
    /*
    * 要求：
    * 统计文件夹中每一种文件的个数
    * */
    public static void main(String[] args) {
        File file = new File("a04FileTest");
        HashMap<String,Integer> hm = fileCount(file);
        System.out.println(hm);
        for(Map.Entry<String,Integer> entry : hm.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }

    public static HashMap<String,Integer> fileCount(File f){
        File[] files =f.listFiles();
        HashMap<String,Integer> hm = new HashMap<>();
        if(files==null) return hm;
        for(File file : files){
            if(file.isFile()){
                String[] filename=file.getName().split("\\.");
                int len=filename.length;
                if(len>=2){//存在后缀文件名
                    String sort = filename[len-1];
                    if(hm.containsKey(sort)){
                        int count = hm.get(sort) + 1;
                        hm.put(sort,count);
                    }else {
                        hm.put(sort,1);
                    }
                }else{
                    hm.put(filename[0], 1);
                }
            }else{//该文件为文件夹
                HashMap<String,Integer> sonhm = fileCount(file);
                for(Map.Entry<String,Integer> entry : sonhm.entrySet()){
                    String key = entry.getKey();
                    if(hm.containsKey(key)){
                        int count = entry.getValue()+hm.get(key);
                        hm.put(key,count);
                    }else{
                        hm.put(key,entry.getValue());
                    }
                }
            }
        }
        return hm;
    }
}
